package gui;

import java.awt.Canvas;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

import common.SpinBox;

import switcher.ImageSwitcher;
import switcher.SpinBoxSwitcher;
import switcher.TimeSwitcher;

public class SwitchGui extends JFrame {

	private static final long serialVersionUID = -5719142061132613952L;

	ImageSwitcher imgs = new ImageSwitcher();
	TimeSwitcher ts = new TimeSwitcher();
	SpinBoxSwitcher sbs = new SpinBoxSwitcher();

	Timer timer; // swing控件中的定时器
	String strTime;

	JLabel lblTime = new JLabel();
	Canvas cvBox = new Canvas();
	JLabel lblImage = new JLabel();

	public SwitchGui() {
		super("转发器");
		this.setLayout(new FlowLayout());
		this.add(lblTime);

		cvBox.setSize(70, 70);
		this.add(cvBox);

		this.add(lblImage);

		this.setLocation(100, 100);
		this.setSize(400, 300);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setVisible(true);

		final int delay = 200; // 200ms
		ActionListener taskPerformer = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				refresh();
			}
		};
		timer = new Timer(delay, taskPerformer);
		timer.start();

		imgs.start();
		ts.start();
		sbs.start();

		// 开启组播
		imgs.enableBroadcast();
		ts.enableBroadcast();
		sbs.enableBroadcast();
	}

	// 刷新界面显示
	private void refresh() {
		// System.out.println("OOO");
		try {
			strTime = "Time: " + ts.getTimeString();
			lblTime.setText(strTime);
			
			SpinBox.paint(sbs.getSpinBox(), cvBox.getGraphics(), 70);
			
			if (imgs.getImage() != null)
				lblImage.setIcon(new ImageIcon(imgs.getImage()));
		} catch (Exception ex) {
			System.out.println(ex);
		}
	}

	public static void main(String[] args) {
		new SwitchGui();

	}

}
